import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import config from '../config'
const { api_base_url } = config

let instance = axios.create({
    baseURL: api_base_url,
    timeout: 1000,
    // headers: {'Access-Control-Allow-Origin': '*'}  
});


instance.defaults.responseType = 'json';   //表示服务器响应的类型
// instance.defaults.withCredentials = true;  //跨域时是否需要凭证
instance.defaults.transformRequest = [     //允许在向服务器发送前，修改请求数据
    // 对 data 进行任意转换处理
    data => {
        return qs.stringify(data)
    }
]

// 请求拦截器
instance.interceptors.request.use(
    config => {
        if(localStorage.getItem('dt_ptyub7')) {
            const token = localStorage.getItem('dt_ptyub7')
            const { requestname: key, str: value } = JSON.parse(token);
            config.method === 'get' ? (config.params[key] = value) : (config.data[key] = value);
        }        
        // console.log('config.data',config)
       
        return config

    },
    error => {
        Message.error({ message: '请求超时!' });
        return Promise.reject(error)
    }
)




// 响应拦截器即异常处理
instance.interceptors.response.use(
    response => {
        let data = response.data
        let status = response.status
    
        // console.log('响应拦截器',response)
        if (!data.hasOwnProperty('success')) {
            return Promise.resolve(response)
        } else if(data.success) {
            return Promise.resolve(response)
        } else if(!data.success) {
            if (data.code === 0) {
                Message.error({ message: `${data.msg}` });
            } else if(data.code === 1 || data.code === 2) {
                Message.error({ message: `${data.msg}` });
                // window.location.href = '/demo/zhongheng/zhpc/pages/y_login.html'
            }
            return Promise.reject(data);
        }
    },
    error => {
        return error
    }
)  

let ajaxMethod = ['get', 'post']
let api = {}
ajaxMethod.forEach(method => {
    api[method] = function (uri, data, config) {
        return new Promise(function (resolve, reject) {
            instance[method](uri, data, config)
            .then(response => { // 这里拿到的是响应器处理过的数据
                // console.log('最终响应：',response)
                if (response.status === 200) {
                    // console.log(response.data)
                    resolve(response.data)
                }
            })
            .catch(error => {
                reject(error)
            })            
        })
    }
})

export default api